package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.Merchant;
import cn.edu.tju.elm.service.MerchantService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.tju.core.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@RequestMapping("/merchant")
public class MerchantController {

    @Autowired
    private MerchantService merchantService;

    @PostMapping
    public HttpResult create(@RequestBody Merchant merchant) {
        boolean saved = merchantService.save(merchant);
        return saved ? HttpResult.ok(merchant) : HttpResult.fail("create failed");
    }

    @PutMapping("/{id}")
    public HttpResult update(@PathVariable Integer id, @RequestBody Merchant merchant) {
        merchant.setId(id);
        boolean updated = merchantService.updateById(merchant);
        return updated ? HttpResult.ok(merchant) : HttpResult.fail("update failed");
    }

    @DeleteMapping("/{id}")
    public HttpResult delete(@PathVariable Integer id) {
        boolean removed = merchantService.removeById(id);
        return removed ? HttpResult.ok(true) : HttpResult.fail("delete failed");
    }

    @GetMapping("/{id}")
    public HttpResult get(@PathVariable Integer id) {
        Merchant merchant = merchantService.getById(id);
        return merchant != null ? HttpResult.ok(merchant) : HttpResult.fail("not found");
    }

    @GetMapping("/list")
    public HttpResult list(@RequestParam(required = false) String businessName,
                       @RequestParam(required = false) BigDecimal minRating,
                       @RequestParam(required = false) BigDecimal maxDeliveryFee,
                       @RequestParam(defaultValue = "1") long page,
                       @RequestParam(defaultValue = "10") long size) {
        QueryWrapper<Merchant> qw = new QueryWrapper<>();
        if (businessName != null && businessName.trim().length() > 0) {
            qw.like("business_name", businessName.trim());
        }
        if (minRating != null) {
            qw.ge("rating", minRating);
        }
        if (maxDeliveryFee != null) {
            qw.le("delivery_fee", maxDeliveryFee);
        }
        Page<Merchant> p = merchantService.page(new Page<>(page, size), qw);
        return HttpResult.ok(p);
    }
}


